import {getLyric, getSongUrl} from "@/api/song";
import {commonConfig, options} from "@/config/api-config/config";
import {Base64} from 'js-base64'
import {jsonp} from "@/common/js/jsonp";
import axios from "axios";
import {rankSong_format} from "@/api/rank";
import {searchSong_format} from "@/api/search";

export default class Song {
    constructor({id,mid,name,album,time,img,url,singer}) {
        this.id = id
        this.mid = mid
        this.name = name
        this.album = album
        this.time = time
        this.url = url
        this.img = img
        this.singer = singer
    }

   async getLyric(){
        if(this.lyric)
            return this.lyric

       this.lyric = Base64.decode(await getLyric(this.mid))
       return this.lyric
    }
}

const debug = process.env.NODE_ENV !== 'production'

//获取指定歌手歌曲列表
export async function getSong(mid) {
    const url = 'https://c.y.qq.com/v8/fcg-bin/fcg_v8_singer_track_cp.fcg'
    const data = {
        g_tk: 1928093487,
        inCharset: 'utf-8',
        outCharset: 'utf-8',
        notice: 0,
        format: 'jsonp',
        hostUin: 0,
        needNewCode: 0,
        platform: 'yqq',
        order: 'listen',
        begin: 0,
        num: 80,
        songstatus: 1,
        singermid: mid
    }
    let result = await jsonp(url,data,options)
    return format_song(result.data.list)
}

//获取歌单歌曲列表
export async function getDiscSong(dissid) {
    const url = debug ? '/api/discsong' : 'http://ustbhuangyi.com/music/api/getDiscList'
    let param = {
        type: 1,
        json: 1,
        utf8: 1,
        onlysong: 0,
        new_format: 1,
        disstid: dissid,
        g_tk_new_20200303: 5381,
    }
    const query = Object.assign({},commonConfig,param)
    let result = await axios.get(url,{
        params:query
    })

    return format_song(result.data)
}

//获取排行榜歌曲
export async function getRankSong(topid) {
    const url = 'https://c.y.qq.com/v8/fcg-bin/fcg_v8_toplist_cp.fcg'
    const data = {
        g_tk: 1928093487,
        inCharset: 'utf-8',
        outCharset: 'utf-8',
        notice: 0,
        format: 'jsonp',
        topid,
        needNewCode: 1,
        uin: 0,
        tpl: 3,
        page: 'detail',
        type: 'top',
        platform: 'h5'
    }
    let ret = await jsonp(url,data,options)
    return format_song(rankSong_format(ret.songlist))
}

//获取搜索歌曲
export async function search (query, page, zhida, perpage) {
    const url = debug ? '/api/search' : 'http://ustbhuangyi.com/music/api/search'
    const data ={
        w: query,
        p: page,
        perpage,
        n: perpage,
        catZhida: zhida ? 1 : 0,
        zhidaqu: 1,
        t: 0,
        flag: 1,
        ie: 'utf-8',
        sem: 1,
        aggr: 0,
        remoteplace: 'txt.mqq.all',
        uin: 0,
        needNewCode: 1,
        platform: 'h5',
        format: 'json',
        g_tk: 1928093487,
        inCharset: 'utf-8',
        outCharset: 'utf-8',
        notice: 0
    }

    let ret = (await axios.get(url, {
        params: data
    })).data
    let message = ret.message
    if(message == 'no results'){
        console.log('no result')
        return null
    }
    return format_song(searchSong_format(ret.data.song.list))
}

/* helper functions */
export async function format_song(list) {
    let ret = []
    for (let i = 0; i < list.length; i++){
        let {musicData} = list[i]
        if(isValidMusic(musicData))
            ret.push(createSong(musicData))
    }
    return await processSongUrl(ret)
}

export function createSong(musicData) {
    return new Song({
        id: musicData.songid,
        mid: musicData.songmid,
        name: musicData.songname,
        album: musicData.albumname,
        time: musicData.interval,
        img: `https://y.gtimg.cn/music/photo_new/T002R300x300M000${musicData.albummid}.jpg?max_age=2592000`,
        url: musicData.url,
        singer: fliterSinger(musicData.singer)
    })
}

export function fliterSinger(singer) {
    if(!singer)
        return ''
    let ret = []
    singer.forEach(item => {
        ret.push(item.name)
    })
    return ret.join(' / ')
}

function isValidMusic(musicData) {
    return musicData.songid && musicData.albummid && (!musicData.pay || musicData.pay.payalbumprice === 0)
}

export async function processSongUrl(songs) {
    if(!songs.length)
        return songs
    let purlMap = await getSongUrl(songs)
    if(!purlMap)    return
    songs = songs.filter(song => {
        const purl = purlMap[song.mid]
        if(purl){
            song.url = purl.indexOf('http') === -1 ? `http://dl.stream.qqmusic.qq.com/${purl}` : purl
            return true
        }
        return false
    })
    return songs
}
